//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package gitcode_triger

import (
	"encoding/json"
	"fmt"

	"atomgit.com/openlinksaas-org/api-server/triger_impl/core"
)

type PrSourceInfo struct {
	GitHttpUrl string `json:"git_http_url"`
	GitSshUrl  string `json:"git_ssh_url"`
	WebUrl     string `json:"web_url"`
}

type PrTargetInfo struct {
	GitHttpUrl string `json:"git_http_url"`
	GitSshUrl  string `json:"git_ssh_url"`
	WebUrl     string `json:"web_url"`
}

type PrObjectAttrsInfo struct {
	Iid          int          `json:"iid"`
	CreatedAt    string       `json:"created_at"`
	UpdatedAt    string       `json:"updated_at"`
	Title        string       `json:"title"`
	SourceBranch string       `json:"source_branch"`
	TargetBranch string       `json:"target_branch"`
	Source       PrSourceInfo `json:"source"`
	Target       PrTargetInfo `json:"target"`
}

type PrHookInfo struct {
	ObjectAttrs PrObjectAttrsInfo `json:"object_attributes"`
}

func ExtractPrHookAttr(data []byte) ([]string, error) {
	obj := &PrHookInfo{}

	err := json.Unmarshal(data, obj)
	if err != nil {
		return nil, err
	}

	retList := []string{
		fmt.Sprintf("%s=%s", core.GIT_HOOK_TYPE, "pr"),
		fmt.Sprintf("%s=%d", core.GIT_PR_ID, obj.ObjectAttrs.Iid),
		fmt.Sprintf("%s=%s", core.GIT_PR_CREATE_AT, obj.ObjectAttrs.CreatedAt),
		fmt.Sprintf("%s=%s", core.GIT_PR_UPDATE_AT, obj.ObjectAttrs.UpdatedAt),
		fmt.Sprintf("%s=%s", core.GIT_PR_TITLE, obj.ObjectAttrs.Title),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_BRANCH, obj.ObjectAttrs.SourceBranch),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_WEB_URL, obj.ObjectAttrs.Source.WebUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_HTTP_URL, obj.ObjectAttrs.Source.GitHttpUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_SSH_URL, obj.ObjectAttrs.Source.GitSshUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_BRANCH, obj.ObjectAttrs.TargetBranch),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_WEB_URL, obj.ObjectAttrs.Target.WebUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_HTTP_URL, obj.ObjectAttrs.Target.GitHttpUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_SSH_URL, obj.ObjectAttrs.Target.GitSshUrl),
	}
	return retList, nil
}
